package cn.tedu.tmall.admin.content.filter;

import cn.tedu.tmall.common.pojo.CurrentUser;
import cn.tedu.tmall.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    private String HEADER_AUTHORIZATION = "Authorization";
    private String secretKey = "fdsfads0000dxcfdfds3fsdfdsfdsfdsf";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        log.debug("进入用户验证过滤器（完全免登录模式）");
        String requestURI = request.getRequestURI();
        log.debug("当前请求地址:{}", requestURI);
        response.setContentType("application/json;charset=UTF-8");

        // -------------- 核心逻辑：无论是否有JWT，都注入“全权限匿名用户” --------------
        // 1. 创建匿名用户（固定信息，无需实际登录）
        CurrentUser anonymousUser = new CurrentUser();
        anonymousUser.setId(0L); // 匿名用户ID（自定义）
        anonymousUser.setUsername("anonymous"); // 匿名用户名

        // 2. 授予“所有接口访问权限”（/** 匹配所有路径）
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("/**")); // 关键：允许访问所有接口

        // 3. 注入到Spring Security上下文，让框架认为“已认证且有权限”
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                anonymousUser, null, authorities);
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(authentication);

        log.debug("已注入全权限匿名用户，直接放行所有请求");
        filterChain.doFilter(request, response);
    }
}